<template>
  <a-modal
    v-model:open="visible"
    title="编辑角色"
    :width="600"
    :confirm-loading="loading"
    ok-text="确认"
    cancel-text="取消"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
      class="role-form"
    >
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="角色名称" name="roleName">
            <a-input
              v-model:value="formData.roleName"
              placeholder="请输入角色名称"
              size="large"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="角色描述" name="prompt">
            <a-textarea
              v-model:value="formData.prompt"
              placeholder="请详细描述这个角色的特点、背景和重要信息..."
              :rows="4"
              :max-length="500"
              show-count
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="音色选择" name="voiceId">
            <a-select
              v-model:value="formData.voiceId"
              placeholder="请选择音色"
              size="large"
              :loading="voiceLoading"
              show-search
              :filter-option="false"
              :not-found-content="voiceLoading ? '加载中...' : '暂无数据'"
            >
              <a-select-option
                v-for="voice in voiceList"
                :key="voice.id"
                :value="voice.id"
              >
                <div>
                  <div>{{ voice.voiceName }}</div>
                  <div v-if="voice.description" class="voice-desc">{{ voice.description }}</div>
                </div>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="知识库" name="knowledgeId">
            <a-select
              v-model:value="formData.knowledgeId"
              placeholder="选择知识库（可选）"
              size="large"
              allow-clear
              :loading="knowledgeLoading"
            >
              <a-select-option 
                v-for="knowledge in knowledgeList" 
                :key="knowledge.id" 
                :value="knowledge.id"
              >
                {{ knowledge.name }}
                <span v-if="knowledge.isDefault === 1" class="default-kb-tag">（默认知识库）</span>
                <span v-if="knowledge.description" class="knowledge-desc"> - {{ knowledge.description }}</span>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="角色头像" name="avatar">
            <div class="avatar-upload">
              <a-upload
                v-model:file-list="fileList"
                name="avatar"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                :before-upload="beforeUpload"
                :custom-request="handleAvatarUpload"
              >
                <div v-if="formData.avatarUrl" class="avatar-preview">
                  <img :src="formData.avatarUrl" alt="avatar" />
                </div>
                <div v-else class="upload-placeholder">
                  <CloudUploadOutlined />
                  <div class="upload-text">上传头像</div>
                </div>
              </a-upload>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { CloudUploadOutlined } from '@ant-design/icons-vue'
import type { FormInstance, UploadChangeParam, UploadProps } from 'ant-design-vue'
import roleService, { type ExtendedRole } from '@/api/roleService'
import { Codewin } from '@/api/generated/Codewin'
import { useAuthStore } from '@/stores/modules/auth'
import { useResourceStore } from '@/stores'

// 获取认证store
const authStore = useAuthStore()
const resourceStore = useResourceStore()



// Props 和 Emits
interface Props {
  open: boolean
  role?: ExtendedRole | null
}

interface Emits {
  'update:open': [value: boolean]
  'success': [role: ExtendedRole]
}

const props = withDefaults(defineProps<Props>(), {
  open: false,
  role: null
})

const emit = defineEmits<Emits>()

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()
const fileList = ref<any[]>([])

// 使用resource store中的数据
const voiceList = computed(() => resourceStore.voices)
const voiceLoading = computed(() => resourceStore.voicesLoading)
const knowledgeList = computed(() => resourceStore.allKnowledgeBases)
const knowledgeLoading = computed(() => resourceStore.knowledgeBasesLoading || resourceStore.defaultKnowledgeBasesLoading)

// API实例
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api'
})



// 表单数据
const formData = reactive({
  roleName: '',
  prompt: '',
  voiceId: '',
  knowledgeId: '',
  avatarUrl: ''
})

const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 1, max: 50, message: '角色名称长度在1-50个字符', trigger: 'blur' }
  ],
  prompt: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { min: 10, max: 500, message: '角色描述长度在10-500个字符', trigger: 'blur' }
  ],
  voiceId: [
    { required: true, message: '请选择音色', trigger: 'change' }
  ]
}

// 监听 props 变化
watch(() => props.open, (newVal) => {
  visible.value = newVal
  if (newVal && props.role) {
    nextTick(() => {
      loadRoleData();
    })
  }
})

watch(visible, (newVal) => {
  emit('update:open', newVal)
  if (!newVal) {
    resetForm()
  }
})

// 方法
const loadRoleData = () => {
  if (props.role) {
    // 只处理必选字段和头像
    formData.roleName = props.role.roleName || ''
    formData.prompt = props.role.prompt || ''
    // 由于后端RoleVo不返回voiceId和knowledgeId，使用默认值
    formData.voiceId = props.role.voiceId || '';
    // console.log(formData)
    formData.knowledgeId = props.role.knowledgeId || ''
    formData.avatarUrl = props.role.avatar || ''
  }
}

// 获取音色列表 - 现在使用resource store
const fetchVoiceList = async () => {
  try {
    await resourceStore.fetchVoices()
  } catch (error) {
    console.error('获取音色列表失败:', error)
    message.error('获取音色列表失败')
  }
}

// 获取知识库列表 - 现在使用resource store
const fetchKnowledgeList = async () => {
  try {
    await resourceStore.fetchKnowledgeBases()
    await resourceStore.fetchDefaultKnowledgeBases()
  } catch (error) {
    console.error('获取知识库列表失败:', error)
    message.error('获取知识库列表失败')
  }
}

const resetForm = () => {
  formData.roleName = ''
  formData.prompt = ''
  formData.voiceId = ''
  formData.knowledgeId = ''
  formData.avatarUrl = ''
  fileList.value = []
  if (formRef.value) {
    formRef.value.resetFields()
  }
}



const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return true // 允许上传，由custom-request处理
}

// 头像上传处理函数
const handleAvatarUpload: UploadProps['customRequest'] = async (options) => {
  const { file, onSuccess, onError } = options
  if (file instanceof File) {
    try {
      // 设置Authorization header
      const headers: Record<string, string> = {}
      if (authStore.token) {
        headers['Authorization'] = `Bearer ${authStore.token}`
      }
      
      const response = await api.uploadFile({ file }, {
        headers
      })
      
      if (response.data?.code === 0 && response.data?.data) {
        formData.avatarUrl = response.data.data
        message.success('头像上传成功！')
        onSuccess?.(response.data.data)
      } else {
        throw new Error('上传失败')
      }
    } catch (error) {
      console.error('头像上传失败:', error)
      message.error('头像上传失败，请重试')
      onError?.(error as Error)
    }
  }
}

// 组件挂载时获取音色列表和知识库列表 - 现在使用resource store
onMounted(() => {
  // 如果resource store中没有数据，则获取
  fetchVoiceList();
  fetchKnowledgeList();
})

const handleSubmit = async () => {
  if (!props.role) return
  
  try {
    loading.value = true
    
    // 表单验证
    await formRef.value?.validate()
    
    // 准备提交数据 - 只包含后端API需要的字段
    const submitData = {
      roleName: formData.roleName,
      prompt: formData.prompt,
      voiceId: formData.voiceId || '',
      knowledgeId: formData.knowledgeId || '',
      avatarUrl: formData.avatarUrl || ''
    }
    
    // 调用更新接口
    await roleService.updateRole(props.role.id, submitData )
    
    // 显示成功提示
    message.success('角色更新成功')
    
    // 触发成功事件，传递包含头像的完整数据
    const updatedRole = {
      ...props.role,
      ...formData,
      knowledgeId: formData.knowledgeId || ''
    }
    emit('success', {
      ...updatedRole,
      knowledgeId: formData.knowledgeId ? String(formData.knowledgeId) : undefined
    })
    
    // 关闭模态框
    visible.value = false
  } catch (error) {
    console.error('更新角色失败:', error)
    
    // 根据错误类型提供具体的错误提示
    let errorMessage = '角色更新失败'
    if (error instanceof Error) {
      if (error.message.includes('网络')) {
        errorMessage = '网络连接失败，请检查网络后重试'
      } else if (error.message.includes('权限')) {
        errorMessage = '没有权限执行此操作'
      } else if (error.message.includes('服务器')) {
        errorMessage = '服务器错误，请稍后重试'
      } else {
        errorMessage = error.message
      }
    }
    message.error(errorMessage)
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  visible.value = false
}
</script>

<style scoped>
.role-form {
  padding: 8px 0;
}

.voice-desc {
  color: #999;
  font-size: 12px;
}

.knowledge-desc {
  color: #999;
  font-size: 12px;
}

.default-kb-tag {
  color: #1890ff;
  font-size: 12px;
  font-weight: 500;
}

.tags-input-container {
  width: 100%;
}

.tags-display {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.avatar-upload {
  display: flex;
  justify-content: flex-start;
}

.avatar-uploader {
  width: 120px;
  height: 120px;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  background: #fafafa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-placeholder:hover {
  border-color: #6366f1;
  color: #6366f1;
}

.upload-text {
  margin-top: 8px;
  font-size: 12px;
}

:deep(.ant-upload-select-picture-card) {
  width: 120px;
  height: 120px;
  border-radius: 8px;
}
</style>